<template>
	<view class="bgw">
		<view class="item text-center font-bold">
			{{title || '成本明细表'}}
		</view>
		<u-line></u-line>
		<u-tabs :list="tabs" @click="tabClick" :activeStyle="activeStyle" lineColor="#675f91" :current="current">
			<view slot="right" style="padding-right: 10px;">
				<view class="flex" v-if="!readonly && (tabs[current].id == 'manual_input' || tabs[current].id == 'am' || tabs[current].id == 'dp')">
					<u-button type="primary" size="mini" text="添加" @click="add"></u-button>
				</view>
			</view>
		</u-tabs>
		<view class="bg-gray">
			<view class="flex font-24 text-light-gray">
				<template v-for="(col,i) in tableHd">
					<view :style="[col.style]" class="">
						<view class="tableHd-item text-center">
							{{col.title}}
						</view>
					</view>
				</template>
			</view>
		</view>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" style="max-height: 250px;min-height: 250px;height: 250px;"
			@scroll="scroll" v-if="!readonly && (tabs[current].id == 'manual_input' || tabs[current].id == 'am' || tabs[current].id == 'dp')">
		<!-- <view class="" style="min-height: 250px;"
			v-if="!readonly && (tabs[current].id == 'manual_input' || tabs[current].id == 'am' || tabs[current].id == 'dp')"> -->
			<template v-for="(v,i) in currentList">
				<view class="" :id="'item'+i">
					<view class="blank10"></view>
					<view class="flex">
						<template v-for="col in tableHd">
							<view :style="[col.style]" v-if="col.key == 'del'">
								<view class="">
									<u-icon name="trash" color="#E40A0C" size="16" @click="bindDel(v.id)"></u-icon>
								</view>
							</view>
							<view class="text-center flex-1" v-else-if="col.key == 'cost_amount'">
								<view class="table-item">
									<input v-model="cost_amount[v.id]" type="number" placeholder="请输入" :maxlength="8"
										@blur="cost_amount_blur" @input="cost_amount_input" :data-id="v.id"
										class="input_border_bottom" />
								</view>

							</view>
							<view class="text-center flex-1" v-else-if="col.key == 'amdp_amount'">
								<view class="table-item">
									<input v-model="amdp_amount[v.id]" type="number" placeholder="请输入" :maxlength="8"
										@blur="amdp_amount_blur" @input="amdp_amount_input" :data-id="v.id"
										class="input_border_bottom" />
								</view>
							</view>
							<view :style="[col.style]" v-else-if="col.key == 'rel_partner_id'">
								<view class="table-item">
									<!-- <liuDataSelect :elementId="'select'+i" :dataList="dataList" @change="rel_partner_change">
										<input v-model="rel_partner_name[v.id]" type="text" placeholder="请输入" :maxlength="8"
											class="input_border_bottom" :id="'select'+i" />
									</liuDataSelect> -->
									<view class="text-center table-item">
									{{v.rel_partner_id[1]}}
								</view>
								</view>
							</view>
							<view :style="[col.style]" v-else-if="col.key == 'cost_obj_id'">
								<view class="text-center table-item">
									{{v.cost_obj_id[1]}}
								</view>
							</view>
							<view :style="[col.style]" v-else>
								<view class="text-center table-item">
									{{v[col.key]}}
								</view>
							</view>

						</template>
					</view>
					<view class="blank10"></view>
					<u-line dashed></u-line>
				</view>
				<!-- <view class="flex item">
					<view class="text-center" style="width: 40%;">
						{{v.name}}
					</view>
					<view class="text-center flex-1" v-if="!readonly">
						<input v-model="qty[i]" type="number" placeholder="请输入" class="input_border_bottom" />
					</view>
					<view class="text-center flex-1" v-if="readonly">
						{{qty[i]}}
					</view>
				</view> -->

			</template>
		<!-- </view> -->
		</scroll-view>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" style="max-height: 250px;min-height: 250px;height: 250px;"
			@scroll="scroll" v-else>
			<template v-for="(v,i) in currentList">
				<view class="" :id="'item'+i">
					<view class="blank10"></view>
					<view class="flex">
						<template v-for="(col,i) in tableHd">
							<view :style="[col.style]" v-if="col.key == 'del'">

							</view>

							<view :style="[col.style]" v-else-if="col.key == 'rel_partner_id'">
								<view class="text-center table-item">
									{{v.rel_partner_id[1]}}
								</view>
							</view>
							<view :style="[col.style]" v-else-if="col.key == 'cost_obj_id'">
								<view class="text-center table-item">
									{{v.cost_obj_id[1]}}
								</view>
							</view>
							<view :style="[col.style]" v-else>
								<view class="text-center table-item">
									{{v[col.key]}}
								</view>
							</view>
						</template>
					</view>
					<view class="blank10"></view>
					<u-line dashed></u-line>
				</view>
			</template>

		</scroll-view>
		<view class="wrapper bg-gray">
			<view class="blank10"></view>
			<view class="flex">
				<view class="text-light-gray">总成本：</view>
				<view class="font-bold">{{cost_amount_sum}}</view>
				<view class="flex ml15" v-if="!readonly && errorTip">
					<u-icon name="close-circle" color="#D6251F" size="14" class="mr10"></u-icon>
					<text class="text-red">{{errorTip}}</text>
				</view>
			</view>
			<view class="blank10"></view>
		</view>
		<view class="blank20"></view>
		<view class="wrapper">
			<view class="flex">
				<view class="flex-1" v-if='readonly'>
					<u-button type="info" text="关闭" size="small" @click="cancel"></u-button>
				</view>
				<view class="flex-1 mr10" v-if='!readonly'>
					<u-button type="info" text="取消修改" size="small" @click="cancel"></u-button>
				</view>
				<view class="flex-1 ml10" v-if='!readonly'>
					<u-button type="primary" text="保存修改" size="small" @click="confirm"></u-button>
				</view>
			</view>
		</view>
		<view class="blank20"></view>
	</view>
</template>

<script>
	import {
		update_cost_report_data
	} from '@/common/api.js';
	// import liuDataSelect from '@/components/liu-data-select/liu-data-select.vue';
	let am_dp_tableHd = [{
			title: '成本对象',
			key: 'cost_obj_id',
			style: {
				width: '300rpx'
			},
		},
		{
			title: '折旧摊销(元)',
			key: 'amdp_amount',
			style: {
				flex: 1
			},
		},
		{
			title: '',
			key: 'del',
			style: {
				width: '50rpx'
			},
		},
	];
	export default {
		name: "cost-record",
		props: {
			title: String,
			classfication: String,
			date: String,
			list: Array,
			category: Array,
			readonly: Boolean,
		},
		components: {
			// liuDataSelect
		},
		data() {
			return {
				allList: this.list,
				max_cost: 0,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				cost_amount: {},
				amdp_amount: {},
				booked_cost_amount: {},
				current: 0,
				activeStyle: {
					color: '#675f91'
				},
				tabs: [],
				tabsConfig: {
					manual_input: {
						name: '人工录入',
						tableHd: [{
								title: '交易对象',
								key: 'rel_partner_id',
								style: {
									width: '300rpx'
								},
							},
							{
								title: '成本(元)',
								key: 'cost_amount',
								style: {
									flex: 1
								},
							},
							{
								title: '备注',
								key: 'cost_obj_id',
								style: {
									width: '300rpx'
								},
							},
							{
								title: '',
								key: 'del',
								style: {
									width: '50rpx'
								},
							},
						],

					},
					am: {
						name: '摊销',
						tableHd: JSON.parse(JSON.stringify(am_dp_tableHd))
					},
					dp: {
						name: '折旧',
						tableHd: JSON.parse(JSON.stringify(am_dp_tableHd))
					},
					stock_in: {
						name: '入库',
						tableHd: [{
								title: '交易对象',
								key: 'rel_partner_id',
								style: {
									width: '200rpx'
								},
							},
							{
								title: '成本对象',
								key: 'cost_obj_id',
								style: {
									width: '200rpx'
								},
							},
							{
								title: '成本(元)',
								key: 'cost_amount',
								style: {
									flex: 1
								},
							},
							{
								title: '备注',
								key: 'note',
								style: {
									width: '200rpx'
								},
							}
						]
					},
					stock_out: {
						name: '出库',
						tableHd: [{
								title: '成本(元)',
								key: 'booked_cost_amount',
								style: {
									flex: 1
								},
							},
							{
								title: '备注',
								key: 'note',
								style: {
									flex: 1
								},
							}

						]
					}
				},
				cost_classfication: 'manual_stock_in_out', //[manual_stock_in_out] -人工入库出库。 [dp] - 折日。 [am] -摊销
				currentList: [],
				del_ids: [],
				errorTip: '',
				cost_amount_sum: 0,
				dataList: ['选项1', '选项2', '选项3', '选项4', '选项5', '选项6', '选项7', '选项8', '选项9', '选项10']
			};
		},
		created() {
			// console.log(this.list);
			let userInfo = this.$store.getters.get_userInfo;
			this.max_cost = userInfo['通用配置'].max_cost || 0;

			this.cost_amount = {};
			this.amdp_amount = {};
			this.booked_cost_amount = {};
			this.allList.forEach((v, i) => {
				this.cost_amount[v.id] = v.cost_amount;
				this.amdp_amount[v.id] = v.amdp_amount;
				this.booked_cost_amount[v.id] = v.booked_cost_amount;
			})
			this.setTabs();

		},
		filters: {

		},
		watch: {
			cost_amount: {
				handler(newVal, oldVal) {
					// console.log('11')
					this.set_cost_amount_sum();
				},
				immediate: false,
				deep: true
			},
			amdp_amount: {
				handler(newVal, oldVal) {
					this.set_cost_amount_sum();
				},
				immediate: false,
				deep: true
			}

		},
		computed: {
			tableHd() {
				let id = this.tabs[this.current].id;
				let tableHd = this.tabsConfig[id].tableHd;
				return tableHd;
			}
		},
		methods: {
			change(e) {
				console.log(e)

			},
			set_cost_amount_sum() {
				let cost_amount_sum = 0;
				this.allList.forEach(v => {
					if (v.cost_classfication == 'am' || v.cost_classfication == 'dp') {
						cost_amount_sum += Number(this.amdp_amount[v.id] || 0);
					} else if (v.cost_classfication == 'stock_out') {
						cost_amount_sum += Number(this.booked_cost_amount[v.id] || 0);
					} else if(v.cost_classfication == 'manual_input'){
						cost_amount_sum += Number(this.cost_amount[v.id] || 0);
					}
				})
				if (cost_amount_sum < 0) {
					this.errorTip = '总成本不得小于0';
				} else if (!this.max_cost) {
					this.errorTip = '';
				} else if (cost_amount_sum > this.max_cost) {
					this.errorTip = '总成本超出最大值' + this.max_cost;
				} else {
					this.errorTip = '';
				}
				this.cost_amount_sum = this.formatPrice(cost_amount_sum);
			},
			setTabs() {
				if (this.classfication == 'am') {
					this.tabsConfig.am.show = true;
				}
				if (this.classfication == 'dp') {
					this.tabsConfig.dp.show = true;
				}
				if (this.classfication == 'manual' || this.classfication == 'manual_stock_in_out') {
					this.tabsConfig.manual_input.show = true;
				}
				this.allList.forEach(v => {
					try {
						this.tabsConfig[v.cost_classfication].show = true;
					} catch (e) {
						// console.log(v.cost_classfication)
					}

				})
				let tabs = [];
				for (let tab in this.tabsConfig) {
					if (this.tabsConfig[tab].show) {
						let _lengtn = this.allList.filter(v => v.cost_classfication == tab).length;
						tabs.push({
							id: tab,
							name: this.tabsConfig[tab].name,
							badge: {
								value: _lengtn,
							}
						})
					}
				}
				this.current = 0;
				this.tabs = tabs;
				this.setCurrentList();
			},
			updataTabs() {
				let tabs = this.tabs;
				tabs.forEach((v, i) => {
					let _lengtn = this.allList.filter(d => d.cost_classfication == v.id).length;
					tabs[i].badge.value = _lengtn;
				})
				this.tabs = tabs;

			},
			setCurrentList() {
				this.currentList = this.allList.filter(v => v.cost_classfication == this.tabs[this.current].id)
				this.scrollTop = this.old.scrollTop
				this.$nextTick(function() {
					this.scrollTop = 0
				});
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			add() {
				let cost_classfication = this.tabs[this.current].id;
				let data = {
					cost_classfication: cost_classfication,
					cost_category_id: this.category,
				};
				this.$emit("add", data);
				// console.log(data);
				this.allList.push(data);
				this.currentList.push(data);
				this.cost_amount[data.id] = '';
				this.updataTabs();
				// let _length = this.detail.childs.push(data);
				// this.errorsQty.push('');
				// this.tipsQty.push('');
				// this.errorsPrice.push('');
				// this.price.push('');
				// this.qty.push('');
				// this.show = true;
				// console.log(data);
			},
			bindDel(id) {
				this.remove(id, true);
				if ((id + '').startsWith('virtual')) {
					this.remove(id, true);
					return;
				}
				this.remove(id);
				// this.$store.dispatch('modal', '确认删除？').then(() => {
				// 	this.remove(id);
				// })
			},
			remove(id, isAdd) {
				this.allList = this.allList.filter((v, i) => v.id != id);
				this.currentList = this.currentList.filter((v, i) => v.id != id);
				this.updataTabs();
				this.set_cost_amount_sum();
				if (!isAdd) {
					this.del_ids.push(id);
				}
			},
			tabClick(e) {
				this.current = e.index;
				this.setCurrentList();
			},
			cost_amount_blur(e) {
				let id = e.target.dataset.id;
			},
			amdp_amount_blur(e) {
				let id = e.target.dataset.id;
			},
			cost_amount_input(e) {
				let id = e.target.dataset.id;
				if (this.cost_amount[id] + '' != '') {
					let num = Number(this.cost_amount[id]);
					// if(num>100000000){
					// 	num = Number((num+'').substr(0,9));
					// }
					this.cost_amount[id] = num;
				}
				this.set_cost_amount_sum();

			},
			amdp_amount_input(e) {
				let id = e.target.dataset.id;
				if (this.amdp_amount[id] + '' != '') {
					let num = Number(this.amdp_amount[id]);
					if (num > 100000000) {
						num = Number((num + '').substr(0, 9));
					}
					this.amdp_amount[id] = num;
				}
				this.set_cost_amount_sum();
			},
			save() {

			},
			check() {

			},
			confirm() {
				if (this.errorTip) {
					uni.$u.toast(this.errorTip);
					return;
				}
				let obj_list = [];
				let new_list = [];
				this.allList.forEach(v => {
					let cost_amount = Number(this.cost_amount[v.id] || 0);
					let amdp_amount = Number(this.amdp_amount[v.id] || 0);
					let item = {
						...v,
						cost_amount: cost_amount,
						amdp_amount: amdp_amount
					}
					new_list.push(item);
					obj_list.push({
						...item,
						cost_category_id: item.cost_category_id[0],
						cost_obj_id: item.cost_obj_id[0] || 0,
						rel_partner_id: item.rel_partner_id[0] || 0,
						cost_center_id: item.cost_center_id[0] || 0
					})
				});
				let vals = {
					cost_category_id: this.category[0],
					date: this.date,
					obj_list: obj_list,
					unlink_ids: this.del_ids
				};
				uni.showLoading({
					title: '正在提交',
					mask: true
				});
				let cost_amount_sum = this.cost_amount_sum;
				update_cost_report_data({
					vals: vals
				}).then((res) => {
					console.log(res);
					res.result.forEach((v, i) => {
						new_list[i].id = v.id;
					})
					this.$emit("confirm", {
						cost_amount: cost_amount_sum,
						list: new_list
					});
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
				})


				// this.save(()=>{
				// 	let list = JSON.parse(JSON.stringify(this.list));
				// 	let flag = false;
				// 	let cost_amount = 0;
				// 	list.forEach((v, i) => {
				// 		v.cost_amount = Number(this.cost_amount[v.id]);
				// 		if (v.cost_classfication == 'am' || v.cost_classfication == 'dp') {
				// 			cost_amount += v.amdp_amount;
				// 		} else if (v.cost_classfication == 'stock_out' || v.cost_classfication == 'manual_input') {
				// 			cost_amount += v.cost_amount;
				// 		}
				// 	})
				// 	let data = {
				// 		cost_amount: cost_amount,
				// 		list:list,
				// 		del_ids:this.del_ids
				// 	};
				// 	this.$emit("confirm", data);
				// });


				// if (flag) {
				// 	this.$emit("confirm", data);
				// } else {
				// 	this.$emit("cancel");
				// }
			},
			cancel() {
				this.$emit("cancel");
			}
		}

	}
</script>

<style>
	.tableHd-item {
		padding: 10upx 5upx;
	}

	.table-item {
		padding: 10upx 10upx;
	}

	.btn-info {
		width: 600rpx;
		height: 88rpx;
		margin: 0 auto;
		margin-top: 30rpx;
		border: solid #f0f0f0 1px;
		border-radius: 12rpx;
		padding: 0 30rpx;
	}
</style>